const Koa = require('koa')
const path = require('path')
const fs = require('fs')
const app = new Koa()
const { readTestFileDir } = require('./utils/index')
const tmlFile = './tml/t.html'
const cors = require('koa2-cors') /* 跨域必需模块 */
const bodyParser = require('koa-bodyparser') /* POST请求必需模块 */
app.use(cors())
app.use(bodyParser())
const logger = require('koa-logs-middleware')
app.use(logger({
  defaultPath: path.resolve(__dirname, 'logs'),
  applicationName: 'app',
  auto: true
}))
// 开发输入日志
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = (new Date()).getTime() - start.getTime()
  ctx.logger.info(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

const Router = require('koa-router')
const subject = require('./control/subject')
const test = require('./control/test')
const send = require('koa-send')
const router = new Router()
const minify = require('html-minifier').minify
const utils = require('./utils')

const buildOneTestFile = id => {
  const data = test.getId(id)
  // 2. 读入模板
  let originHtml = fs.readFileSync(path.join(__dirname, tmlFile), 'utf8')

  // 3. 替换，填入数据
  originHtml = originHtml.replace(/const d=\{.*\}/, `const d=${JSON.stringify(data)}`)

  // 4. 文件加密
  // minifyJS
  const encodeHtml = minify(originHtml, {
    removeAttributeQuotes: true,
    removeComments: true,
    collapseWhitespace: true,
    minifyJS: { compress: { drop_console: true } },
    minifyCSS: true,
    sortClassName: true
  })
  // eslint-disable-next-line no-debugger
  // 5.写入
  const fileName = utils.buildTestFileSave(data)
  const _t = path.join(__dirname, 'files/' + fileName)
  fs.writeFileSync(_t, encodeHtml)
}
router.get('/', async (ctx) => {
  ctx.body = { message: '', data: '这是首页' }
})

// 获取题目列表
router.get('/api/subject', async (ctx) => {
  const data = subject.get()
  ctx.body = { message: '', data: data }
})

// 获取题目详情
router.get('/api/subject/:id', async (ctx) => {
  // 获取动态路由的传值
  const id = ctx.params.id
  const data = subject.getId(id)
  ctx.body = { message: '', data: data }
})

// 添加题目
router.post('/api/subject', async (ctx) => {
  const subObj = ctx.request.body
  const data = subject.add(subObj)
  ctx.body = { message: '', data: data }
})

// 全量修改题目
router.put('/api/subject', async (ctx) => {
  const subObj = ctx.request.body
  const data = subject.put(subObj)
  ctx.body = { message: '', data: data }
})

// patch修改题目
router.patch('/api/subject', async (ctx) => {
  const subObj = ctx.request.body
  const data = subject.patch(subObj)
  ctx.body = { message: '', data: data }
})

// 删除题目
router.delete('/api/subject', async (ctx) => {
  const { id } = ctx.request.body
  console.log('api/subject.........', id)
  const data = subject.del(id)
  ctx.body = { message: '', data: data }
})

// 添加题目
router.post('/api/testSubject', async (ctx) => {
  const { testId, subId } = ctx.request.body
  const data = test.addSub(testId, subId)
  ctx.body = { message: '', data: data }
})
// 删除试卷中的题目
router.delete('/api/testSubject', async (ctx) => {
  const { testId, subId } = ctx.request.body
  console.log('delete /api/testSubject .........', testId, subId)
  const data = test.delSub(testId, subId)
  ctx.body = { message: '', data: data }
})

// 添加测试
router.post('/api/test', async (ctx) => {
  const testObj = ctx.request.body // {ids, testName}
  const data = test.add(testObj)
  ctx.body = { message: '', data: data }
})

// 获取测试列表
router.get('/api/test', async (ctx) => {
  const data = test.get()
  ctx.body = { message: '', data: data }
})

// 获取单套测试
router.get('/api/test/:id', async (ctx) => {
  // 获取动态路由的传值
  const dt = ctx.params.id
  console.log(ctx.params) // { aid: '123', cid: '456' }
  const data = test.getId(dt)

  ctx.body = { message: '', data: data }
})

// 生成测试试卷
router.post('/api/test/create', (ctx) => {
  // 1. 根据参数读出数据
  const { ids } = ctx.request.body
  ids.forEach(id => {
    buildOneTestFile(id)
  })
  ctx.body = { message: '', data: '生成试卷ok' }
})

// 下载已有的测试
router.get('/api/test/download/:id', async (ctx) => {
  // 1. 根据参数读出数据
  const id = ctx.params.id
  const testFileList = readTestFileDir()
  const fileName = testFileList.find(it => it.startsWith(id)) + '.html'
  const _t = path.join(__dirname, 'files/' + fileName)
  const stat = fs.statSync(_t)
  if (stat) {
    ctx.attachment(_t)

    // 导出
    const encodePath = 'serve/files/' + fileName
    await send(ctx, encodePath)
  } else {
    ctx.body = { message: '', data: { err: 0 } }
  }
})

// 导出题目
router.get('/api/test/export/:id', async (ctx) => {
  // 1. 根据参数读出数据
  const id = ctx.params.id
  const data = test.getId(id)
  // 2. 读入模板
  let originHtml = fs.readFileSync(path.join(__dirname, tmlFile), 'utf8')

  // 3. 替换，填入数据
  originHtml = originHtml.replace(/const d=\{.*\}/, `const d=${JSON.stringify(data)}`)

  // 4. 文件加密
  // minifyJS
  const encodeHtml = minify(originHtml, {
    removeAttributeQuotes: true,
    removeComments: true,
    collapseWhitespace: true,
    minifyJS: { compress: { drop_console: true } },
    minifyCSS: true,
    sortClassName: true
  })
  // eslint-disable-next-line no-debugger
  // 5.写入
  const fileName = utils.buildTestFileSave(data)
  const _t = path.join(__dirname, 'files/' + fileName)
  fs.writeFileSync(_t, encodeHtml)
  ctx.attachment(_t)

  // 6. 导出
  const encodePath = 'serve/files/' + fileName
  await send(ctx, encodePath)
})

router.get('/news', async (ctx) => {
  ctx.body = { message: '', data: '这是新闻页' }
})

router.get('/home', async (ctx) => {
  ctx.body = { message: '', data: '这是home页面' }
})

app
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(3004, () => {
  console.log('3004')
})

module.exports = {}
